<template>
  <div>
    <el-dialog title="多图上传" :visible.sync="dialogVisible" :show-close="false" @close="clear" :center="true"
      :lock-scroll="true" custom-class="import-data-dlg" append-to-body>
      <div class="tip">建议尺寸：建议图片宽度750px，高度按750宽度等比例缩放，可以拖拽图片调整顺序，最多上传10张</div>
      <div class="images">
        <draggable id="content-box flex-item" v-model="localImageList" dragable="true" @update="datadragEnd">
          <template v-for="(item, key) in localImageList">
            <div class="pic-bar mar-r-30 flex-item" :key="key" @mouseover.stop="itemOver(key)"
              @mouseout.stop="itemOut(-1)" v-loading="item.fileLoading">
              <div @click="deleteImgages(item,key)">
                <svg-icon icon-class="close" :class="{'active':key==curIndex || key==curHover}"
                  class="close-icon font-16 noraml-hide" />
              </div>
              <img class="picture" :src="item.imageUrl" />
              <div class="uploader--fail" v-if="item.isError">上传失败!</div>
            </div>
          </template>
        </draggable>
        <el-upload class="mar-t-10" :action="action" :data="data" name="files" :show-file-list="false" ref="uploader"
          multiple :limit="10" :on-exceed="handleExceed" accept=".png,.jpg,.jpeg" :before-upload="beforeUpload"
          :on-success="handleUploadSuccess" :on-error="handleUploadError" list-type="picture-card">
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer pull-right">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="ok">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import draggable from 'vuedraggable'

  export default {
    name: 'MultiFileUpload',
    components: {
      draggable
    },
    props: {
      dialogVisible: Boolean,
      action: String,
      data: Object,
      onConfirm: Function,
      onCancel: Function,
      // 是否要返回图片的宽高
      isReturnFileWidthHeight: Boolean
    },
    data: function() {
      return {
        fileLoading: false,
        curIndex: -1,
        curHover: -1,
        dialogShow: false,
        localImageList: []
      }
    },
    methods: {
      beforeUpload(file) {
        var that = this
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        // 是否要返回图片的宽高
        if (this.isReturnFileWidthHeight) {
          var imgOjb = URL.createObjectURL(file)
          var img = new Image()
          img.src = imgOjb
          img.onload = function() {
            that.localImageList.forEach(item => {
              if (item.uid === file.uid) {
                item.fileWidth = img.width
                item.fileHeight = img.height
              }
            })
          }
        }
        this.localImageList.push({
          imageUrl: '',
          uid: file.uid,
          mainImageFlag: 0,
          isError: false,
          fileLoading: true,
          fileName: file.name,
          fileSize: file.size
        })
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        if (res.code === 101) {
          this.localImageList.forEach(item => {
            if (item.uid === file.uid) {
              item.fileLoading = false
              item.imageUrl = res.data[0]
            }
          })
          this.setMainImageFlag()
        } else {
          this.uploadError(file)
        }
      },
      handleUploadError(res, file) {
        if (file.status === 'fail') {
          this.localImageList.forEach(item => {
            if (item.uid === file.uid) {
              item.isError = true
              item.fileLoading = false
              item.imageUrl = file.url
            }
          })
        }
        this.$message.warning('网络异常，请稍后再试(504)')
      },
      uploadError(file) {
        this.$message.warning('网络异常，请稍后再试(504)')
      },
      handleExceed(file, fileList) {
        // 文件超出个数限制时的钩子
        this.$message.warning('一次只能上传10张图片')
      },
      ok() {
        // 按顺序返回
        this.onConfirm(this.localImageList)
        this.clear()
      },
      cancel() {
        this.onCancel()
      },
      clear() {
        this.onCancel()
        this.localImageList = []
        this.$refs.uploader.clearFiles()
      },
      datadragEnd(evt) {
        evt.preventDefault()
        const filters = this.localImageList
        for (let a = 0; a < filters.length; a++) {
          filters[a].index = a
        }
        this.localImageList = filters
      },
      itemOver(index) {
        this.curHover = index
      },
      itemOut(index) {
        this.curHover = index
      },
      deleteImgages(item, key) {
        const goodsImages = this.localImageList
        // 获取elemetUI upload中上传的数组 同步删除
        const fileList = this.$refs.uploader.uploadFiles
        const index = fileList.findIndex(item => {
          return item.uid === goodsImages[key].uid
        })
        if (index !== -1) {
          fileList.splice(index, 1)
        }
        goodsImages.splice(key, 1)
        this.localImageList = goodsImages
        this.setMainImageFlag()
      },
      setMainImageFlag() {
        const goodsImages = this.localImageList
        goodsImages.forEach((item, index) => {
          if (index === 0) {
            item.mainImageFlag = 1
          } else {
            item.mainImageFlag = 0
          }
        })
        this.localImageList = goodsImages
      }
    },
    watch: {
      dialogVisible: function(newData) {
        this.dialogShow = newData
      }
    }
  }
</script>
<style lang="scss" scoped>
  .import-data-dlg {
    height: 720px;

    .el-dialog__body {
      padding-top: 0;
      padding-bottom: 0;

      .tip {
        font-size: 13px;
        color: #99a9bf;
        text-align: center;

        span {
          color: #000;
        }

        &.bottom {
          margin-top: 20px;
          text-align: left;
        }
      }

      .images {
        overflow-y: auto;
        padding-top: 20px;
        height: 540px;
        width: 100%;
        margin: auto;
      }

      .upload-images {
        text-align: center;
        padding-top: 150px;

        &.has-files {
          padding-top: 35px;
        }

        .el-upload-list--picture-card .el-upload-list__item {
          width: 120px;
          height: 120px;
          margin: 0 20px 20px 0;
          border-radius: 0;

          img {
            object-fit: cover;
          }

          &::after {
            position: absolute;
            display: inline-block;
            bottom: 0;
            left: 0;
            right: 0;
            height: 35px;
            line-height: 35px;
            color: white;
            font-size: 13px;
            background: rgba(0, 0, 0, .5);
          }

          &.is-error::after {
            content: '网络错误';
          }

          &.is-bigger::after {
            content: '大于2M';
          }
        }

        .el-upload-list--picture-card {
          .el-progress {
            width: 100px;

            .el-progress-circle {
              width: 100px !important;
              height: 100px !important;
            }
          }
        }

        .el-upload--picture-card {
          width: 120px;
          height: 120px;
          line-height: 118px;
          border-radius: 0;
        }
      }
    }
  }

  .pic-bar {
    position: relative;
    display: inline-block;
    margin-bottom: 10px;

    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .picture {
    width: 148px;
    height: 148px;
    display: block;
  }

  .noraml-hide {
    display: none !important;
  }

  .active {
    display: block !important;
  }

  .dialog-footer {
    .el-dialog__footer {
      position: absolute;
      bottom: 20px;
      width: 100%;
    }
  }

  .uploader--fail {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: white;
    background: rgba(0, 0, 0, 0.7);
  }
</style>
